(function() {

  function array_count_values(array) {
    var tmp_arr = {},
      key = '',
      t = '';
    var __getType = function(obj) {
      // Objects are php associative arrays.
      var t = typeof obj;
      t = t.toLowerCase();
      if (t === 'object') {
        t = 'array';
      }
      return t;
    };
    var __countValue = function(value) {
      switch (typeof value) {
        case 'number':
          if (Math.floor(value) !== value) {
            return;
          }
          // Fall-through
        case 'string':
          if (value in this && this.hasOwnProperty(value)) {
            ++this[value];
          } else {
            this[value] = 1;
          }
      }
    };
    t = __getType(array);
    if (t === 'array') {
      for (key in array) {
        if (array.hasOwnProperty(key)) {
          __countValue.call(tmp_arr, array[key]);
        }
      }
    }
    return tmp_arr;
  }

  function array_intersect(arr1) {
    var retArr = {},
      argl = arguments.length,
      arglm1 = argl - 1,
      k1 = '',
      arr = {},
      i = 0,
      k = '';
    arr1keys: for (k1 in arr1) {
      arrs: for (i = 1; i < argl; i++) {
        arr = arguments[i];
        for (k in arr) {
          if (arr[k] === arr1[k1]) {
            if (i === arglm1) {
              retArr[k1] = arr1[k1];
            }
            // If the innermost loop always leads at least once to an equal value, continue the loop until done
            continue arrs;
          }
        }
        // If it reaches here, it wasn't found in at least one array, so try next value
        continue arr1keys;
      }
    }
    return retArr;
  }

  /**
   * 判断是否在sku里面
   */
  function isInSkuList(obj) {
    //    console.log(obj)
    if (skuList instanceof Array) {
      var stockObj = {};
      var tmp = [];
      for (var k in obj) {
        var tmpObj = {};
        for (var i in skuList) {
          if (parseInt(skuList[i]['stock']) == 0) {
            var tmpProperty = skuList[i]['property'];
            for (var j in tmpProperty) {
              if (j == k && tmpProperty[j] == obj[k]) {
                tmpObj[skuList[i]['id']] = skuList[i]['property'];
              }
            }
          }
        }
        tmp.push(tmpObj)
      }
      //      console.log(tmp)
      tmpLength = tmp.length;
      if (tmpLength == 1) {
        stockObj = tmp[0];
      } else {
        stockObj = tmp[0];
        for (var i = 0; i < tmp.length; i++) {
          stockObj = array_intersect(tmp[i], stockObj);
        }
      }

      var combTotal = 1;
      for (var i in propertyIds) {
        combTotal *= propertyIds[i];
      }

      var checkComb = 1;
      for (var i in obj) {
        checkComb *= propertyIds[i];
      }

      var newStockObj = [];
      for (var j in propertyIds) {
        //        if (!obj[j]) {
        for (var i in stockObj) {
          newStockObj.push(j + '-' + stockObj[i][j]);
        }
        //        }
      }
      //      console.log(newStockObj)
      countObj = array_count_values(newStockObj);
      //      console.log(countObj)
      var tmpCountObj;
      var unableObj = {};
      for (var i in countObj) {
        tmpCountObj = i.split('-');
        selfComb = propertyIds[tmpCountObj[0]];
        maxCount = combTotal / checkComb / selfComb;
        if (countObj[i] >= maxCount) {
          unableObj[tmpCountObj[1]] = tmpCountObj[0];
        }
      }
      //      console.log(unableObj)
      return unableObj;
    }
    return false;
  }

  /**
   * 获取一个sku info
   */
  function getSkuInfo(obj) {
    if (skuList instanceof Array) {
      for (var i = 0; i < skuList.length; i++) {
        var property = skuList[i]['property'];
        var propertyLength = 0;
        var tmpLength = 0;
        for (var j in property) {
          propertyLength++
          if (obj[j] == property[j]) {
            tmpLength++
          }
        }
        if (propertyLength == tmpLength) {
          return skuList[i];
        }
      }
    }
    return null;
  }

  /**
   * 检查不能购买的sku
   */
  function checkSkuList(thisObj) {
    var obj = {};
    var checkedObj = [];
    for (var i in propertyIds) {
      var tmp = $('.property' + i).val();
      if (tmp) {
        obj[i] = tmp;
        $('.js_sku' + i).each(function() {
          var dataVal = $(this).data('property_value_id');
          if (dataVal == tmp) {
            checkedObj.push($(this).data('value'));
          }
        })
      }
    }
    $('.js_checkSku').html(checkedObj.join('/')).show().prev().show();
    var unableObj = isInSkuList(obj);
    //    console.log(unableObj)
    if ($.isEmptyObject(unableObj) == true) {
      $('.js_sku').each(function() {
        if (thisObj.closest('.p').data('property_id') != $(this).closest('.p').data('property_id')) {
          if ($(this).hasClass('unable')) {
            $(this).removeClass('unable');
          }
        }
      });
    } else {
      for (var i in unableObj) {
        $('.property' + unableObj[i]).find('.a').each(function() {
          var propertyValueId = $(this).data('property_value_id');
          if (i == propertyValueId) {
            $(this).addClass('unable');
          }
        });
      }
    }
    //    console.log(unableObj)
  }

  setInterval(function() {
    $.get(siteUrl + "/goods/get_sku_list?r=" + (new Date).getTime(), {
      id: goodsId
    }, function(json) {
      if (json.sku_list) {
        // 克隆
        skuList = $.extend([], json.sku_list);
        //        console.log(1);
      }
    }, 'json');
  }, 30000);



  $(function() {
    $('.share-wraps').hover(function() {
      $('#newbd_share_menu').show();
    }, function() {
      $('#newbd_share_menu').hide();
    })

    $('.js_sku').click(function() {
      var propertyValueId = $(this).data('property_value_id');
      var propertyId = $(this).closest('.p').data('property_id');

      if ($(this).hasClass('curr')) {
        $('.property' + propertyId).val('');
        $(this).removeClass('curr');
        checkedSkuId = 0;
        checkSkuList($(this));
        $('.js_skuNum').data('stock', stock);
        return false;
      }

      if ($(this).hasClass('unable')) {
        return false;
      }

      $('.property' + propertyId).val(propertyValueId);

      $(this).addClass('curr').siblings().removeClass('curr');
      var obj = {};

      for (var i in propertyIds) {
        var tmp = $('.property' + i).val();
        if (tmp) {
          obj[i] = tmp;
        }
      }
      // console.log(obj);
      var sku_info = getSkuInfo(obj);
      if (sku_info) {
        $('.js_price').text(' ￥' + sku_info.price);
        $('.js_skuNum').data('stock', sku_info.stock);
        checkedSkuId = sku_info.id;
        $.post(
          siteUrl + '/goods/get_sku_cover', {
            id: checkedSkuId
          },
          function(data) {
            if (data && data.info == 'ok') {
              $('.jqzoom').html('<img jqimg="' + data.big + '" src="' + data.list + '" />')
            } else {
              if ($(this).hasClass('js_icon')) {
                var listIcon = $(this).data('list_icon');
                var bigIcon = $(this).data('big_icon');
                $('.jqzoom').html('<img jqimg="' + bigIcon + '" src="' + listIcon + '" />')
              }
            }
          },
          'json'
        );
      }
           // console.log(sku_info);
      checkSkuList($(this));
    })

    $('.car-btn').click(function() {
      //加入检测代码
      var s=s_gi(s_account);
      s.linkTrackVars="events,products";
      s.linkTrackEvents="scAdd";
      s.products=";"+goodsId; //记录产品的 ID 唯一标识 s.events=”scAdd”;
      s.tl(this,'o','shopping cart');

      /*if (flagship == 1 && flagship_link) {
        location.href=flagship_link;
        return false;
      }*/
      thisBtn = $(this);
      if (!checkedSkuId) {
        $.scrollTo('body', 400, function() {
          showMsg('请选择要购买的商品属性')
        });
        return false;
      }
      var goodsNum = $('.js_skuNum').val();

      $.ajax({
        type: "POST",
        url: siteUrl + "/goods/get_stock",
        async: false,
        data: {
          sku_id: checkedSkuId
        },
        dataType: "json",
        success: function(data) {
          if (data.info != 'ok') {
            showMsg('数据错误，请稍候再试', 'error');
            return false;
          }
          if (parseInt(goodsNum) > parseInt(data.stock)) {
            showMsg('选择商品库存不够');
            return false;
          }
          addGoodsToCart(checkedSkuId, goodsNum, function(data) {
            if (data.info == 'ok') {
              $('.js_buyCartNumber').html(data.cart_num);
              showMsg('添加到购物车成功', 'success');
              thisBtn.data('buy', 'true');
            }
          })
        }
      })
    })

    $('.buy-btn').click(function() {
      /*if (flagship == 1 && flagship_link) {
        location.href=flagship_link;
        return false;
      }*/
      if (!checkedSkuId) {
        $.scrollTo('body', 400, function() {
          showMsg('请选择要购买的商品属性');
        });
        return false;
      }
      var isPromotion = $(this).data('is_promotion');
      if(!isPromotion || isPromotion != 1) {
        isPromotion = 0;
      }
      var goodsNum = parseInt($('.js_skuNum').val());
      if (!goodsNum) {
        showMsg('请选择要购买的商品属性');
        return;
      }
      var thisBtn = $(this);
      $.ajax({
        type: "POST",
        url: siteUrl + "/goods/get_stock",
        async: false,
        data: {
          sku_id: checkedSkuId
        },
        dataType: "json",
        success: function(data) {
          if (data.info != 'ok') {
            showMsg('数据错误，请稍候再试', 'error');
            return false;
          }
          if (parseInt(goodsNum) > parseInt(data.stock)) {
            showMsg('选择商品库存不够');
            return false;
          }

          // 跳转到直接购买
          if (data.is_direct_buy == 1 || thisBtn.data('is_direct_buy') == 1) {
            //...
            location.href = siteUrl + "/order/trade?sku_id=" + checkedSkuId + "&num=" + goodsNum;
            return;
          }

          addGoodsToCart(checkedSkuId, goodsNum, function(data) {
            if (data.info == 'ok') {
              location.href = siteUrl + "/cart";
            }
          }, isPromotion)
        }
      })
    })

    $('.collect').click(function() {
      var thisBtn = $(this);
      var url = '';
      if (thisBtn.hasClass('curr-collect')) {
        url = siteUrl + '/fav/delete';
      } else {
        url = siteUrl + '/fav/save';
      }
      $.ajax({
        type: 'post',
        url: url,
        async: true,
        data: {
          res_id: goodsId,
          res_name: 'goods'
        },
        dataType: 'json',
        success: function(data) {
          if (data.info == 'error') {
            //showMsg(data.msg, 'error');
          } else {
            if (thisBtn.hasClass('curr-collect')) {
              thisBtn.removeClass('curr-collect');
              thisBtn.html('<i class="icon"></i>收藏商品');
            } else {
              thisBtn.addClass('curr-collect');
              thisBtn.html('<i class="icon"></i>已收藏商品');
            }
          }
        }
      })
    })

    $('.js_comment_user').click(function() {
      var thisBtn = $(this);
      var status = thisBtn.data('status');
      var commentId = thisBtn.parent().data('comment_id');
      var userId = thisBtn.parent().data('user_id');
      var num = thisBtn.data('num');
      var newNum = num + 1;
      $.post(
        siteUrl + '/comment/comment_user', {
          comment_id: commentId,
          user_id: userId,
          comment_status: status
        },
        function(data) {
          if (data.info == 'ok') {
            if (status == 1) {
              var html = '有用（' + newNum + '）';
            } else {
              var html = '没用（' + newNum + '）';
            }
            thisBtn.html(html);
          }
        },
        'json'
      );
    })

    // 数量+p
    $('.add').click(function() {
      var stock = $('.js_skuNum').data('stock');
      var currNum = $('.js_skuNum').val();
      currNum = parseInt(currNum) + 1;
      if (currNum >= stock) {
        $(this).addClass('add-disabled');
        currNum = stock;
      }
      $('.sub').removeClass('sub-disabled');
      $('.js_skuNum').val(currNum);
    });

    // 数量 -
    $('.sub').click(function() {
      var currNum = $('.js_skuNum').val();
      currNum = parseInt(currNum) - 1;
      if (currNum <= 1) {
        $(this).addClass('sub-disabled');
        currNum = 1;
      }
      $('.add').removeClass('add-disabled');
      $('.js_skuNum').val(currNum);
    });

    // 强制输入数字
    $('.jsNum').keyup(function() {
      var stock = $('.js_skuNum').data('stock');
      var currNum = $(this).val();
      currNum = parseInt(currNum);
      if (isNaN(currNum)) {
        currNum = '';
      } else if (currNum == 0) {
        currNum = 1;
      } else if (currNum > stock) {
        currNum = stock;
        showMsg('输入的数量不能大于库存');
      }
      $(this).val(currNum);
    });
  });

  // 回到顶部
  scrolTo = function(start, to, sd) {
    $(start).click(function() {
      $.scrollTo(to, sd);
    });
  }
})();